<template>
  <!--class="component-upload-image"-->
  <div class="component-upload-image">
    <el-upload
      :action="dataObj.host"
      :data="dataObj"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      name="file"
      :on-remove="handleRemove"
      :show-file-list="true"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :class="{ hide: fileList.length >= limit }"
      accept="image/png,image/jpg,image/jpeg,image/gif"
    >
      <el-icon class="avatar-uploader-icon"><plus /></el-icon>
    </el-upload>
    <!--&lt;!&ndash; 上传提示 &ndash;&gt;
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      的文件
    </div>-->

    <el-dialog
      v-model="dialogVisible"
      title="预览"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import {policy} from "./policy";
import {getUUID} from "@/utils";
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const fileList = ref([]);
const showTip = computed(
  () => props.isShowTip && (props.fileSize)
);

const dataObj = ref({
  policy: "",
  signature: "",
  key: "",
  ossaccessKeyId: "",
  dir: "",
  host: "",
  // callback:'',
});

watch(() => props.modelValue, val => {
  getFatherNum();
});
function getFatherNum(){
  let fatherNum = props.modelValue;
  if (fatherNum){
    let list = Array.isArray(fatherNum) ? fatherNum : fatherNum.split(",")
    fileList.value = list.map(item => {
      if (typeof item == "string") {
        item = { name: item, url: item };
      }
      return item
    })
  }else {
    fileList.value = [];
  }
}

// 删除图片
function handleRemove(file, files) {
  const findex = fileList.value.map(f => f.name).indexOf(file.name);
  if (findex > -1) {
    fileList.value.splice(findex, 1);
    emit("update:modelValue", listToString(fileList.value));
  }
}

// 上传成功回调
function handleUploadSuccess(res) {
  let imgUrl = `${dataObj.value.host}/${dataObj.value.key}`
  fileList.value.push({ name: imgUrl, url: imgUrl })
  emit("update:modelValue", listToString(fileList.value));
  proxy.$modal.closeLoading();
}

// 上传前loading加载
function handleBeforeUpload(file) {
  let fileName = null;
  if(file.name.length>8){
    fileName = file.name.slice(-8)
  }else {
    fileName = file.name
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  return new Promise((resolve, reject) => {
    policy().then(response => {
      dataObj.value.policy = response.policy;
      dataObj.value.signature = response.signature;
      dataObj.value.ossaccessKeyId = response.accessid;
      // _self.dataObj.key = response.dir + getUUID()+'_${filename}';
      //固定链接长度
      dataObj.value.key = response.dir + getUUID()+"_"+fileName;
      dataObj.value.dir = response.dir;
      dataObj.value.host = response.host;
      proxy.$modal.loading("上传中");
      resolve(true);
    }).catch(err => {
      resolve(false);
    })
  })
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传失败");
  proxy.$modal.closeLoading();
}

// 预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    strs += list[i].url + separator;
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}

  onMounted(() => {

  })
getFatherNum();
</script>

<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
  display: none;
}
// 去掉动画效果
:deep(.el-list-enter-active),
:deep(.el-list-leave-active) {
  transition: all 0s;
}
:deep(.el-list-enter, .el-list-leave-active) {
  opacity: 0;
  transform: translateY(0);
}
  .component-upload-image{
    width: 148px;
    margin-right: 15px;
  }
  .sku_upload{

    :deep(.el-upload--picture-card){
      width: 80px;
      height: 80px;
      .component-upload-image{
        width: 80px;
        margin-right: 0px;
      }
      i{
        margin-top: 25px;
      }
      :deep(.el-upload-list__item){
        width: 80px;
      }
    }
    :deep(.el-upload-list--picture-card .el-upload-list__item){
      width: 80px;
      height: 80px;
    }
  }
</style>
